/**
 * 获取数据类型
 * @param {any} value 需要判断的值
 * @return "String","Object","Array"...
 */
export const getType = function (value) {
  console.log('getType', Object.prototype.toString)
  return Object.prototype.toString.call(value).slice(8, -1)
}

export const isDef = function (val) {
  return val !== undefined && val !== null
}

export const isNumberStr = function (str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

export const deepClone = function (obj) {
  const _toString = Object.prototype.toString
  // null, undefined, non-object, function
  if (!obj || typeof obj !== 'object') {
    return obj
  }
  // DOM Node
  if (obj.nodeType && 'cloneNode' in obj) {
    return obj.cloneNode(true)
  }
  // Date
  if (_toString.call(obj) === '[object Date]') {
    return new Date(obj.getTime())
  }
  // RegExp
  if (_toString.call(obj) === '[object RegExp]') {
    const flags = []
    if (obj.global) {
      flags.push('g')
    }
    if (obj.multiline) {
      flags.push('m')
    }
    if (obj.ignoreCase) {
      flags.push('i')
    }

    return new RegExp(obj.source, flags.join(''))
  }
  const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}
  for (const key in obj) {
    result[key] = deepClone(obj[key])
  }
  return result
}

/**
 * 获取url参数值
 * @param {String} name 参数名称(不传则返回一个全部参数对象)
 */
export const getUrlParam = function (name) {
  let href = window.location.href,
    i = href.indexOf('?')
  if (i < 0) return null
  let str = href.slice(i)
  if (!str) return null
  let arr = str.match(/([^?&=#]+)=([^?&=#/]*)/g)
  if (!arr) return null
  let obj = {}
  arr.forEach((v) => {
    let temp = v.split('=')
    if (temp.length > 0) {
      obj[temp[0]] = temp[1]
    }
  })
  if (name) return obj[name]
  return obj
}

export const isParent = function (obj, parentObj) {
  while (obj != undefined && obj != null && obj.tagName.toUpperCase() != 'BODY') {
    if (obj == parentObj) {
      return true
    }
    obj = obj.parentNode
  }
  return false
}

/**
 * 扁平数据转树
 * @param data 数据对象
 * @param id 数据id属性名
 * @param pid 上一级数据id属性名
 * @param root 根节点值
 */
export const convert2Tree = (data, id = 'id', pid = 'pid', root = '') => {
  if (!id) return console.warn('convert2Tree方法需要传入数据id')
  if (!pid) return console.warn('convert2Tree方法需要传入数据pid')
  let cache = {}
  data.forEach((item) => {
    item.children = []
    cache[item[id]] = item
  })
  return data.filter((item) => {
    if (item[pid] !== root) {
      if (item[pid]) cache[item[pid]].children.push(item)
      return false
    }
    return true
  })
}

/**
 * 对象深度copy赋值
 * @param target 要赋值得对象
 * @param source 取值对象
 */
export const deepAssignObj = (target, source) => {
  for (const k in target) {
    if (target[k] && Object.prototype.toString.call(target[k]) == '[object Object]') {
      if (source[k]) deepAssignObj(target[k], source[k])
    } else if (source.hasOwnProperty(k)) {
      if (source[k] !== null) {
        target[k] = source[k]
      }
    }
  }
}
